package com.mooc.lib_common;

import android.content.res.TypedArray;
import android.graphics.Outline;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewOutlineProvider;

/**
 * @ClassName: ViewHelper$
 * @Description: java类作用描述
 * @Author: 魏靳元
 * @CreateDate: 2022/8/22 08:57
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public class ViewHelper {
    public static final int RADIUS_ALL=0;
    public static final int RADIUS_LEFT=1;
    public static final int RADIUS_TOP=2;
    public static final int RADIUS_RIGHT=3;
    public static final int RADIUS_BOTTOM=4;

    public static void SetViewOutLine(View view, AttributeSet attributes,int defStyleAttr, int defStyleRes){

        TypedArray typedArray = view.getContext().obtainStyledAttributes(attributes, R.styleable.viewOutLineStrategy, defStyleAttr, defStyleRes);
        int radius = typedArray.getDimensionPixelOffset(R.styleable.viewOutLineStrategy_clip_radius, 0);
        int side = typedArray.getIndex(R.styleable.viewOutLineStrategy_clip_side);
        typedArray.recycle();
        SetViewOutLine(view, radius, side);
    }

    public static void SetViewOutLine(View view, int radius, int side) {
        view.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                int width=view.getWidth();
                int height=view.getHeight();
                if(width<=0||height<=0){
                    return;
                }
                if(side!=RADIUS_ALL){
                    int left=0,right=width,top=0,bottom=height;
                    if (side == RADIUS_LEFT) {
                        right += radius;
                    } else if (side == RADIUS_TOP) {
                        bottom += radius;
                    } else if (side == RADIUS_RIGHT) {
                        left -= radius;
                    } else if (side == RADIUS_BOTTOM) {
                        top -= radius;
                    }
                    outline.setRoundRect(left,top,right,bottom,radius);
                }else {
                    if(radius>0){
                        outline.setRoundRect(0,0,width,height,radius );
                    }else {
                        outline.setRect(0, 0, width, height);
                    }
                }
            }
        });
        view.setClipToOutline(radius > 0);
        view.invalidate();
    }

} 
